const recorderManager = uni.getRecorderManager(); //录音
import {
	sizeDeal
} from "../util.js"
import emoji from './emoji.js'
const systemInfo = uni.getSystemInfoSync();
var app = getApp();
export default {
	data() {
		return {
			// 语音录制相关
			voiceText: '按住 说话',
			voiceTis: "手指上滑 取消发送",
			voiceFlg: false,
			voiceStop: false,
			voiceTimer: null,
			voiceLength: 0,
			voicePageY: 0,

			// 输入框行数
			lineCount: 1,
			// 显示工具箱, 用工具箱顶起键盘
			showBoxTools: false,
			// 键盘高度
			keyboardHeight: '',
			// 键盘开启状态
			keyboardStatus: false,
			// 当前点击的表情和工具箱的索引
			currentBoxTools: '',
			// 输入框内容
			textareaVal: '',
			// 语音录制模式和输入模式切换
			isVoice: false,
			// 表情数据
			emojiList: [],
			// 设备底部安全区域高度
			deviceBottom: 0,
			//输入框高度
			textareHeight: 0,
			// 窗口可用高度
			windowHeight: 0,
			// 状态栏高度
			statusBarHeight: 0,
		}
	},
	computed: {
		boxToolsStyles() {
			// 用工具盒子顶起输入框
			let keyboardHeight = this.keyboardHeight || '257'
			let boxHeight = this.isSafeArea ? keyboardHeight : (keyboardHeight - this.getSafeAreaInsets().deviceBottom)

			return { height: this.showBoxTools ? boxHeight + 'px' : 0 }
		}
	},
	created(info) {
		this.windowHeight = systemInfo.windowHeight; // 窗口可用高度
		this.statusBarHeight = systemInfo.statusBarHeight || 0; // 状态栏高度
		// 获取底部安全区域高度 兼容苹果X 以上机型 
		if (this.isSafeArea) {
			this.deviceBottom = this.getSafeAreaInsets().deviceBottom

			if (!this.deviceBottom) {
				// 安全区域下边界坐标 - 屏幕可用高度 = 底部安全区高度
				this.deviceBottom = systemInfo.safeAreaInsets?.bottom || 0;
			}

			// 或者更兼容的写法：
			// if (systemInfo.safeAreaInsets) {
			// 	this.deviceBottom = systemInfo.safeAreaInsets.bottom;
			// } else {
			// 	// 非全面屏设备返回 0
			// 	this.deviceBottom = 0;
			// }
		}
		// 加载表情
		this.emojiList = emoji

		this.keyboardHeightChange()
		this.onRecorderManager()
	},
	onShow() { },
	onHide() { },
	onUnload() { },
	methods: {
		getSafeAreaInsets() {
			// return plus.navigator.getSafeAreaInsets()
			// const systemInfo = uni.getSystemInfoSync();
			return {
				top: systemInfo.safeAreaInsets?.top || 0,       // 状态栏高度
				right: systemInfo.safeAreaInsets?.right || 0,   // 右侧安全区
				deviceBottom: systemInfo.safeAreaInsets?.bottom || 0, // 底部安全区（iPhone X 等机型为34px）
				left: systemInfo.safeAreaInsets?.left || 0      // 左侧安全区
			};
		},
		// 关闭输入状态
		closeToolsBoxAndKeyboard() {
			// console.log("关闭输入状态")
			this.showBoxTools = false
			this.textareaBlur()
		},

		// 键盘监听
		keyboardHeightChange() {
			console.log('键盘监听')
			uni.onKeyboardHeightChange(res => {
				if (res.height) {
					this.keyboardHeight = res.height
					// this.showBoxTools = true

					if (systemInfo.platform != 'ios') {
						this.keyboardStatus = true;
					}
				} else {
					if (systemInfo.platform != 'ios') {
						this.keyboardStatus = false
					}
					this.showBoxTools = false
					this.textareaBlur()
					if (!this.currentBoxTools) {
						this.showBoxTools = false
					}
				}
				this.textareHeight = this.windowHeight - res.height;
				// console.log('windowHeight', this.windowHeight)
				// console.log('statusBarHeight', this.statusBarHeight)
				// console.log('键盘监听高度：', res.height, this.textareHeight, this.deviceBottom)
			})
		},

		//#region 录音相关


		// 录音监听
		onRecorderManager() {
			// #ifdef MP-WEIXIN ||  APP-NVUE
			//录音开始
			recorderManager.onStart((e) => {
				console.log('录音开始')
			})
			// 录音报错
			recorderManager.onError((e) => {
				console.log(e)
				console.log('录音报错')
			})
			//录音结束
			recorderManager.onStop((e) => {
				console.log('录音结束')
				if (this.voiceStop) {
					uni.showToast({
						icon: "none",
						title: "取消发送"
					})
				} else {
					if (this.voiceLength < 1) {
						uni.showToast({
							icon: "none",
							title: "发送时间过短"
						})
					} else {
						let path = e.tempFilePath
						let name = path.substr(path.lastIndexOf('/') + 1);
						console.log(parseInt(this.voiceLength))
						this.addMsg({
							type: 'sound',
							content: path,
							extend: {
								name: name,
								duration: parseInt(this.voiceLength)
							}
						})
						this.$nextTick(() => {
							this.voiceLength = 0
						})
					}
				}
			})
			// #endif
		},

		// 检测语音时间
		isVoiceTime() {
			if (this.voiceLength < 1) {
				uni.showToast({
					icon: "none",
					title: "发送时间过短"
				})
			} else {
				this.voiceLength = 0
			}
		},
		// 按下触发
		touchstartVoice(e) {
			this.voicePageY = (e.changedTouches[0].pageY).toFixed(2)
			this.voiceText = '松开 结束'
			this.voiceFlg = true
			recorderManager.start({
				format: "mp3",
				sampleRate: 44100,
				numberOfChannels: 1,
				encodeBitRate: 192000
			}); //录音开始,
			this.voiceTimer = setInterval(() => {
				this.voiceLength += 0.1
			}, 100)
			console.log('touchstartVoice', this.voicePageY)
		},
		// 滑动触发
		touchmoveVoice(e) {
			let numTemp = this.voicePageY - ((e.changedTouches[0].pageY).toFixed(2))
			if (numTemp >= 60) {
				console.log('取消发送')
				this.voiceStop = true
				this.voiceTis = "松开手指 取消发送"
			} else {
				console.log('继续发送')
				this.voiceStop = false
				this.voiceTis = "手指上滑 取消发送"
			}
		},
		// 松开触发
		touchendVoice() {
			this.voiceFlg = false
			this.voiceText = '按住 说话'
			this.voiceTis = "手指上滑 取消发送"
			console.log('touchendVoice')
			console.log(this.voiceStop)
			clearInterval(this.voiceTimer);
			this.voiceTimer = null

			recorderManager.stop(); //录音结束
		},
		// 打断触发
		touchcancelVoice() {
			clearInterval(this.voiceTimer);
			this.voiceTimer = null
			this.voiceFlg = false
			this.voiceText = '按住 说话'
			this.voiceTis = "手指上滑 取消发送"
			console.log('touchcancelVoice')
			recorderManager.stop(); //录音结束
		},

		//#endregion


		// 点击工具
		toolItem(item, index) {
			this.$emit('menuClick', item)

			switch (item.type) {
				case 0:
					// console.log('相册')
					// this.getChooseImage(['album']) 弃用
					// this.getChooseVorI(['album'])
					break;
				case 3:
					// console.log('拍摄')
					// this.getChooseImage(['camera']) 弃用
					// this.getChooseVorI(['camera'])
					break;

				default:
			}
		},

		//吊起相册或拍摄
		getChooseImage(type) {
			let _this = this;
			uni.chooseImage({
				sourceType: type,
				count: 9,
				sizeType: ['original', 'compressed'],
				success: async (res) => {
					for (const src of res.tempFilePaths) {
						const name = src.substr(src.lastIndexOf('/') + 1);

						try {
							// 调用 Uni-App 的图片压缩 API
							// #ifdef MP-WEIXIN
							// const compressedRes = await _this.compressImage(src, name);
							// #endif

							// #ifdef H5
							// const compressedRes = await _this.compressImageForH5(src);
							// #endif

							_this.addMsg({
								type: 'image',
								content: src // 直接赋值
							});
						} catch (error) {
							console.error("压缩失败:", error);
							// 压缩失败时使用原图
							_this.addMsg({ type: 'image', content: src });
						}
					}
				},
				fail(err) {
					console.log(err);
					switch (err.errCode) {
						case 2:
							console.log('用户拒绝授权');
							break;
						case 3:
							console.log('接口调用失败');
							break;
					}
				}
			});
		},

		//吊起相册或拍摄 uni
		getChooseVorI(type) {
			let _this = this;
			// #ifdef MP-WEIXIN || MP-ALIPAY || APP-PLUS
			// 选择视频（可同时选图片和视频）
			uni.chooseMedia({
				count: 9, // 最多可选数量
				mediaType: ['image', 'video'], // 只选视频（如需混合选 ['image','video']）
				sourceType: type, // 从相册选择（['camera'] 为拍摄）
				maxDuration: 30, // 视频最大时长（秒）
				success: (res) => {
					// const videos = res.tempFiles.filter(file => file.fileType === 'video');
					res.tempFiles.forEach(item => {
						console.log('文件类型:', item.fileType);
						console.log('文件临时路径:', item.tempFilePath);
						console.log('文件时长:', item.duration);
						console.log('文件封面图:', item.thumbTempFilePath); // 关键属性
						console.log('文件大小:', item.size);
						_this.addMsg({
							type: item.fileType,
							// content: { content: video.tempFilePath, cover: video.thumbTempFilePath },
							content: item.tempFilePath,
							extend: {
								cover: item.thumbTempFilePath
							}
						});
					});
				},
				fail: (err) => {
					console.error('选择失败:', err);
				}
			});
			// #endif

			// #ifdef H5
			// H5使用原生input标签
			const input = document.createElement('input');
			input.type = 'file';
			input.accept = 'image/*,video/*';
			input.multiple = true; // 允许多选
			input.onchange = async (e) => {
				const files = Array.from(e.target.files);
				console.log('H5选择结果:', files);
				// 转换为类似uni的tempFiles结构
				const tempFiles = files.map(file => ({
					tempFilePath: URL.createObjectURL(file),
					fileType: file.type.startsWith('video') ? 'video' : 'image',
					size: file.size,
					name: file.name,
					cover: null,
				}));
				tempFiles.forEach(item => {
					_this.addMsg({
						type: item.fileType,
						content: item.tempFilePath,
						extend: {
							cover: item.thumbTempFilePath
						}
					});
				});
			};
			input.click();
			// #endif
		},

		// 封装压缩方法
		compressImage(src, name) {
			return new Promise((resolve, reject) => {
				uni.compressImage({
					src: src,
					quality: 25, // 压缩质量 (0-100)
					success: (res) => {
						resolve({ target: res.tempFilePath, name });
					},
					fail: (err) => {
						reject(err);
					}
				});
			});
		},

		// H5 专用的压缩方法
		compressImageForH5(file) {
			return new Promise((resolve) => {
				const reader = new FileReader();
				reader.readAsDataURL(file);
				reader.onload = (e) => {
					const img = new Image();
					img.src = e.target.result;
					img.onload = () => {
						const canvas = document.createElement('canvas');
						const ctx = canvas.getContext('2d');
						const maxWidth = 800; // 最大宽度
						const ratio = Math.min(maxWidth / img.width, 1);
						canvas.width = img.width * ratio;
						canvas.height = img.height * ratio;
						ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
						canvas.toBlob((blob) => {
							resolve(URL.createObjectURL(blob));
						}, 'image/jpeg', 0.25); // 质量 0.25
					};
				};
			});
		},

		getBase64(tempFilePath) {
			return new Promise((resolve) => {
				const fileManager = wx.getFileSystemManager()
				fileManager.readFile({
					filePath: tempFilePath,
					encoding: 'base64',
					success: res => resolve(`data:image/jpeg;base64,${res.data}`),
					fail: () => resolve(tempFilePath) // 失败降级
				})
			})
		},

		normalizePath(path) {
			// 处理小程序临时路径
			if (path.startsWith('http://tmp/')) {
				return path.replace('http://', 'https://');
			}
			return path;
		},

		texTlinechange(e) {
			// 获取行高
			this.lineCount = e.detail.lineCount
		},

		// 添加表情
		setEmoj(item, index) {
			this.textareaVal += item
		},

		// 点击发送按钮
		clickMsg() {
			let val = this.textareaVal

			if (val.trim() == '') {
				uni.showToast({
					icon: 'none',
					title: "消息不能为空"
				})
			} else {
				this.textareaVal = ''
				this.$nextTick(() => {
					this.addMsg({ type: 'text', content: val })
				})
			}
			this.closeToolsBoxAndKeyboard()
		},

		// 添加消息
		addMsg({ type, content, extend }) {
			this.$emit('sendMessage', { type, content, extend })
		},

		// 切换语音录制模式
		clickVoice() {
			let isVoice = !this.isVoice

			if (isVoice) {
				this.closeToolsBoxAndKeyboard()
			} else {
				this.textareaFocus()
			}

			setTimeout(() => {
				this.isVoice = isVoice
			}, 50)
		},

		// 点击工具栏
		clickEmoj(i) {
			// this.$emit('menuClick')
			if (i == this.currentBoxTools) {
				this.showBoxTools = !this.showBoxTools
			} else {
				this.showBoxTools = true
			}
			this.currentBoxTools = i
			if (this.keyboardHeight) {
				this.textareaBlur()
			}
			// 点击表情和工具栏，隐藏录音模式
			this.isVoice = false
		},

		onSwiperChange(e) {
			// this.currentBoxTools = e.detail.current;
		},

		// 输入框主动获焦
		textareaFocus() {
			// console.log('输入框获取焦点', this.$refs.textareaRef)
			setTimeout(() => {
				this.$refs.textareaRef && this.$refs.textareaRef.focus()
				console.log('输入框获取焦点2')
			}, 1000)
		},

		// 失去焦点触发
		textareaBlur() {
			// console.log('输入框失去焦点', this.$refs.textareaRef)
			this.$refs.textareaRef && this.$refs.textareaRef.blur()
		},

		tblur() {
			console.log('输入框失去焦点3')
		},


		tfocus() {
			console.log('输入框获得焦点3')
			// this.$emit('menuClick')
		},

		keyboardInput() {
			console.log(222)
		},
	}
};
